const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    reward_points: '',
    avatarInfo: '',
    product: [],
    region: ['浙江省', '杭州市', '江干区'],
    name: '',
    phone: '',
    city: '',
    province: '',
    pid: '',
    address: '',
    len:0,
  },
  onLoad: async function (options) {
    await wx.User.getUserInfo()
    this.setData({
      reward_points: wx.getStorageSync('userinfo').reward_points,
      avatarInfo: wx.getStorageSync('avatarInfo').avatarUrl,
    })

    await wx.User.productsList()
    this.setData({
      product: wx.getStorageSync('productsList'),
      len:wx.getStorageSync('productsList').length
    })
  },
  onShow: function () {

  },
  onProduct: function (e) {
    if (wx.getStorageSync('userinfo').reward_points < e.currentTarget.dataset.price) {
      wx.showToast({
        title: '您的积分不够！',
        icon: 'none'
      })
    } else if(e.currentTarget.dataset.storage ==0) {
      wx.showToast({
        title: '该商品已兑换完，继续加油!',
        icon:'none'
      })
    }else{
      this.setData({
        modalName: 'DialogModal1',
        pid: e.currentTarget.dataset.pid
      })

    }
  },
  hideModal: function () {
    this.setData({
      modalName: null
    })
  },
  RegionChange: function (e) {
    this.setData({
      region: e.detail.value
    })
  },
  nameChange: function (e) {
    this.setData({
      name: e.detail.value
    })
  },
  phoneChange: function (e) {
    this.setData({
      phone: this.validateNumber(e.detail.value)
    })
    if(this.phone==''){
      wx.showToast({
        title: '请输入数字！',
        icon:'none',
        duration:1000
      })
    }
  },
  validateNumber(val) {
    return val.replace(/\D/g, '')
  },
  addressChange: function (e) {
    this.setData({
      address: e.detail.value
    })
  },
  redeemProduct:async function () {
    if (this.data.name == '' || this.data.phone == '' || this.data.address == '') {
      wx.showToast({
        title: '请填写完整信息！',
        icon: 'none'
      })
    } else {
      this.setData({
        province: this.data.region[0],
        city: this.data.region[1],
        address: this.data.region[2] + this.data.address
      })
      await wx.User.redeemProduct({
        data: {
          uid: wx.getStorageSync('userinfo').uid,
          name: this.data.name,
          phone: this.data.phone,
          province: this.data.province,
          city: this.data.city,
          address: this.data.address,
          pid: this.data.pid,
        }
      })
      this.hideModal()
      this.onLoad()
    }

  },
  myRedeem:function(){
    wx.navigateTo({
      url: './myRedeem',
    })
  }
})